package com.axjy.web;

import com.axjy.pojo.Role;
import com.axjy.pojo.User;
import com.axjy.service.RoleService;
import com.axjy.service.UserService;
import com.axjy.util.Log;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Created by asus on 2018/1/30.
 */
@RestController
@RequestMapping("/sys/role")
public class RoleHandler {
    @Resource
    private RoleService roleService;

    @Resource
    private UserService userService;

    @GetMapping("/search")
    public List<Role> search(){
        return roleService.search();
    }

    @PostMapping("/delRole")
    public String delRole(Integer roleId){
        int i=userService.getRoleId(roleId);
        String msg=null;
        if(i==0){
            roleService.delRole(roleId);
            userService.delUser(roleId);
            msg="删除成功！";
        }else{
            msg="该角色下有用户不可以删除！";
        }
        return msg;
    }

    @PostMapping("/addRole")
    public String addRole(Role role,HttpSession session){
        String msg=null;
        User user = (User) session.getAttribute("loginUser");
        try{
            role.setCreatedBy(user.getUserCode());
            roleService.addRole(role);
            msg="新增成功！";
        }catch (RuntimeException ex){
            msg="新增失败！";
            Log.logger.error(msg,ex);
        }
        return msg;
    }

    @PostMapping("/getName")
    public String getName(String roleName){
        String msg=null;
        int i= roleService.getRoleName(roleName);
        if(i>0){
            msg="用户名称已存在";
        }
            Log.logger.error(msg);
        return msg;
    }
}
